// pages/searchpage/searchpage.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list:null,
  },
  // 跳转到点餐界面
  OnClickToOrder: function (e) {
    console.log(e)
    var that = this
    var name = e.currentTarget.dataset.item.s_name;
    var src = e.currentTarget.dataset.item.s_picture;
    var stall = e.currentTarget.dataset.item.s_id;
    var place = e.currentTarget.dataset.item.s_place;
    //保存历史数据到本地
    var history = that.data.history
    var isExist = false
    if(history){
      for (var index = 0; index < history.length; index++) {
        var list = history[index];
        if (list.name == name) {
          isExist = true;
          break;
        }
      }
    }
    if(!isExist){
      if(!history){
        history = []
      }
      history.push({
        name: name,
        src: src,
        stall: stall,
        place:place
      });
      that.setData({
        history: history
      });
      wx.setStorage({
        key: 'searchedHOBO',
        data: history,
        success:function(){
          console.log("保存成功！")
        }
      })
    }
    //跳转进档口
    wx.navigateTo({
      url: '/pages/stopinfo/stopinfo?name=' + name +"&place="+place+  "&stall=" + stall+"&src=" + src ,
      success: function (res) {
        console.log("yes")
      },
      fail: function (res) { },
      complete: function (res) {},
    })
  },
  //历史记录跳转到点餐
  toPagesClick:function(e){
    console.log(e)
    var name = e.currentTarget.dataset.item.name;
    var src = e.currentTarget.dataset.item.src;
    var stall = e.currentTarget.dataset.item.stall;
    var place = e.currentTarget.dataset.item.place;
    wx.navigateTo({
      url: '/pages/stopinfo/stopinfo?name=' + name + "&place=" + place + "&stall=" + stall + "&src=" + src,
    })
  },

  // 在搜索栏输入字符，在数据库中进行模糊查找
  OnClickSearchInput:function(e){
    console.log(e)
    var value = e.detail.value
    // 搜索栏输入的字符
    var that = this
    if(value == ""){
      this.setData({
        ['list']: null
      })
    }else{
      wx.request({
        url: 'http://' + app.globalData.localhost + '/stall/findStallsByFood?&value=' + value,
        success: function (res) {
          console.log(res)
          that.setData({
            ['list']: res.data
          })
        }
      })
    }
  },
  // 点击搜索栏的清除按钮，清空搜索栏和查询列表
  OnCancleClick:function(e){
    this.setData({
      ['list']: null
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var taht = this;
    wx.getStorage({
      key: 'searchedHOBO',
      success: function(res) {
        var data = res.data;
        console.log(data)
        taht.setData({
          history:data
        })
      },fail:function(res){
        console.log(res)
      }
    })
  },

  OnClearEvent:function(event){
    console.log(event)
    wx.removeStorage({
      key: 'searchedHOBO',
      success: function (res) {},
    });
    this.setData({
      history: null
    })
  }

})
